﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Data;
using System.Runtime.Serialization;

namespace MoneyWentWhere.DataModel.Binding
{
    public class AccountList : BindingList<Account>
    {
        public MoneyDataSet DataSet { get; internal set; }
        
        // For use with DataBinding only
        public AccountList() { } 

        public AccountList(MoneyDataSet dataSet) : base() 
        {
            if (dataSet == null) { throw new ArgumentNullException("dataSet"); }

            DataSet = dataSet;
        }
        public AccountList(IList<Account> list) : base(list) { }

        public Account this[String name]
        {
            get
            {
                foreach (Account ac in this)
                {
                    if (ac.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        return ac;
                    }
                }
                return null;
            }
        }

        public void Move(int oldIndex, int newIndex)
        {
            Account ac = this[oldIndex];
            base.RemoveItem(oldIndex);
            base.InsertItem(newIndex, ac);
        }

        protected override void RemoveItem(int index)
        {
            Account a = this[index];

            // Uncouple transfers.
            // Must create a separate list since we're deleting from it
            List<Transaction> txList = new List<Transaction>(a.Transactions);
            foreach (Transaction tx in txList)
            {
                if (tx.TransferToTx != null)
                {
                    // Remove transfer from the other side
                    Transaction otherTx = tx.TransferToTx;
                    otherTx.TransferRemove();
                    otherTx.Comment = "Transfer to deleted acct '" + a.Name + "'. " + otherTx.Comment;
                }
            }


            base.RemoveItem(index); 
        }

        protected override void InsertItem(int index, Account item)
        {
            if (base.Contains(item))
            {
                // QQ: throw or just make it a no-op?
                throw new InvalidOperationException("Account already present: " + item);
            }

            item.DataSet = DataSet;
            base.InsertItem(index, item);
        }
    }

}
